<?php

class OrderController extends BaseController
{
    public function init()
    {
        $this->req = $this->getRequest();
        /* Initialize action controller here */
    }

    public function createAction()
    {
        $req = $this->getRequest();
        if ($req->isPost() == false ) {exit('非法请求');}
        $product_list = $req->getPost('product');
        if ($product_list == false || count($product_list) ==0 ) {exit('未选着商品');}
        $article_id = $req->getPost('article_id');
        if ($article_id == false ) {exit('文章id 不能为空');}

        $product_data = array();
        foreach ($product_list as $id=>$amoout) {
            if ($amoout == 0) continue;
            $product_data[] = array(
                'id' => $id,
                'amount' => $amoout
            );
        }
        // 验证授权信息
        $uid = $this->user_id; // todo user_info
        // 预生成订单
        $article = new \Base\Rest();
        $req = array('uid'=>$uid);
        $post_data = array(
            'article_id'=>$article_id,
            'product_list'=>json_encode($product_data)
        );
        $post = array('payload'=>base64_encode(http_build_query($post_data)));
        $rest_res = $article->post('Order',$req,$post);
        if ($rest_res->isSuccess() == true) {
            $res = $rest_res->getResponse();
            $this->_redirect('/order/pay?id='.$res->order_id);
        } else {
            exit('服务器内部错误');
        }
    }

    public function payAction()
    {
        $id = $this->req->get('id');
        if ($id == false ) {exit('非法请求');}
        $article = new \Base\Rest();
        $req = array('uid'=>$this->user_id); // todo user_info
        $rest_res = $article->get('OrderDetail',$id,$req);
        if ($rest_res->isSuccess()) {
            $res = $rest_res->getResponse();
            $order_dateil = $this->object2array($res);
            $this->view->order_dateil = $order_dateil;
        } else {
            // 没有数据
        }
    }

    private function object2array(&$object) {
        $object =  json_decode( json_encode( $object),true);
        return  $object;
    }
}



